package com.browser.bookmark;

import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.prefs.Preferences;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

@Data
public class BookmarkManager {
    private static final Logger logger = LoggerFactory.getLogger(BookmarkManager.class);
    private final List<Bookmark> bookmarks;
    private final Preferences preferences;
    private final Gson gson;

    public BookmarkManager() {
        this.bookmarks = new ArrayList<>();
        this.preferences = Preferences.userNodeForPackage(BookmarkManager.class);
        this.gson = new Gson();
        loadBookmarks();
    }

    public void addBookmark(String url, String title, String folderId) {
        Bookmark bookmark = new Bookmark(url, title, folderId);
        bookmarks.add(bookmark);
        saveBookmarks();
        logger.info("Added bookmark: {} - {}", title, url);
    }

    public void removeBookmark(String url) {
        bookmarks.removeIf(b -> b.getUrl().equals(url));
        saveBookmarks();
        logger.info("Removed bookmark: {}", url);
    }

    public List<Bookmark> getBookmarks() {
        return new ArrayList<>(bookmarks);
    }

    private void loadBookmarks() {
        String json = preferences.get("bookmarks", "[]");
        List<Bookmark> loaded = gson.fromJson(json, new TypeToken<List<Bookmark>>(){}.getType());
        bookmarks.clear();
        bookmarks.addAll(loaded);
        logger.info("Loaded {} bookmarks", bookmarks.size());
    }

    private void saveBookmarks() {
        String json = gson.toJson(bookmarks);
        preferences.put("bookmarks", json);
        logger.info("Saved {} bookmarks", bookmarks.size());
    }
} 